package com.mpale.soa.base;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Servlet请求
 *
 * @author lijian
 * @date 2020/6/15
 */
public class RequestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String authType = req.getAuthType();
        String contextPath = req.getContextPath();
        System.out.println("authType: " + authType + ",contextPath: " + contextPath);

        String queryString = req.getQueryString();
        String requestURI = req.getRequestURI();
        System.out.println("queryString: " + queryString + ",requestURI: " + requestURI);

        InputStream is = req.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) > 0) {

        }

        String name = req.getParameter("name");
        System.out.println("页面请求参数：" + name);

        ServletContext servletContext = req.getServletContext();
        servletContext.setAttribute("name", name);

        String path = servletContext.getContextPath();
        System.out.println(path);
//        req.getRequestDispatcher("/index.jsp").forward(req, resp);
        resp.sendRedirect(path + "/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
